package com.huangtang.pc.controller;

import com.huangtang.pc.annotation.RateLimit;
import com.huangtang.pc.exception.BizException;
import com.huangtang.pc.pojo.TestUserAO;
import com.huangtang.pc.result.Result;
import com.huangtang.pc.util.RedisUtil;
import com.huangtang.pc.util.SnowflakeIdUtil;
import com.huangtang.pc.util.ThreadLocalUtil;
import com.huangtang.pc.util.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author sunjf
 * @date 2024/01/04
 */

@Slf4j
@Api("测试控制器")
@RestController
@RequestMapping("/test")
public class TestController {

    @ApiOperation("测试接口")
    @GetMapping("/v1")
    @RateLimit
    public Result<String> test(){
        return Result.success("访问成功" + LocalDateTime.now());
    }

    @ApiOperation("抛异常")
    @GetMapping("/exception")
    public void exception(){
//        System.out.println(1/0);
        throw new BizException("异常");
    }

    @ApiOperation("测试Redis")
    @GetMapping("/redis/{key}/{value}")
    public Result<Object> redis(@PathVariable("key") String key,
                                @PathVariable("value") String value){
        RedisUtil.set(key,value);
        return Result.success(RedisUtil.get(key));
    }

    @ApiOperation("测试获取雪花id")
    @GetMapping("/getId")
    public Result<String> getLog() {
        return Result.success(SnowflakeIdUtil.getSnowflakeId());
    }

    @ApiOperation("测试线程工具类")
    @GetMapping("/threadUtl/{key}/{value}")
    public Result<String> threadUtl(@PathVariable("key") String key,
                                    @PathVariable("value") String value) {
        log.info("设置局部变量,key:{},value:{}",key,value);
        ThreadLocalUtil.set(key,value);
        log.info("获取变量并返回:{}", (String) ThreadLocalUtil.get(key));
        ThreadLocalUtil.clearAll();
        ValidateUtil.validate(!Objects.isNull(ThreadLocalUtil.get(key)),"为空错误");
        return Result.success("获取变量并返回:"+ (String) ThreadLocalUtil.get(key));
    }

    @ApiOperation("测试校验参数注解")
    @PostMapping("/validate")
    public Result<Object> validate(@RequestBody @Validated TestUserAO ao){
        return Result.success(ao);
    }
}
